﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using App.Utilities.Web.Handlers;
using System.Data;
using CRMBiz.Group;
using Newtonsoft.Json;

namespace CRMWeb.WebServices.Group
{
    /// <summary>
    /// Summary description for Group
    /// </summary>
    public class Group : BaseHandler
    {
        public override void OnMethodInvoke(OnMethodInvokeArgs e)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
            context.Response.Cache.SetExpires(DateTime.MinValue);
            context.Response.Cache.SetNoStore();

            //e.Cancel = true;

            SetResponseContentType(ResponseContentTypes.HTML);
        }

        public override void AfterMethodInvoke(object result)
        {
            base.AfterMethodInvoke(result);
        }

        //user defined function
        #region private method

        public void GetGroupList()
        {
            try
            {
                var pageIndex = string.IsNullOrEmpty(context.Request["page"]) ? 1 : int.Parse(context.Request["page"]);
                var pageSize = string.IsNullOrEmpty(context.Request["rows"]) ? 10 : int.Parse(context.Request["rows"]);

                DataTable dt = GroupHandler.GetGroupList(pageIndex, pageSize);
                string strJson = JsonConvert.SerializeObject(dt);
                context.Response.Write(strJson);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public void GetGroupDetail(int GroupID)
        {
            try
            {
                DataSet ds = GroupHandler.GetGroupDetail(GroupID);
                string strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                context.Response.Write(strJson);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public bool AddGroup(int ParentGroupID, string GroupName, string GroupType, string Description)
        {
            bool flag = false;
            try
            {
                flag = GroupHandler.AddGroup(ParentGroupID, GroupName, GroupType, Description);
            }
            catch (Exception)
            {
                throw;
            }
            return flag;
        }

        public bool EditGroup(int GroupID, int ParentGroupID, string GroupName, string GroupType, string Description)
        {
            bool flag = false;
            try
            {
                flag = GroupHandler.EditGroup(GroupID, ParentGroupID, GroupName, GroupType, Description);
            }
            catch (Exception)
            {
                throw;
            }
            return flag;
        }

        public int CheckParentGroup(int GroupID, string GroupName, int ParentGroupID)
        {
            int retvalu = 0;
            try
            {
                retvalu = GroupHandler.CheckParentGroup(GroupID, GroupName, ParentGroupID);
            }
            catch (Exception)
            {
                throw;
            }
            return retvalu;
        }

        public bool DeleteGroup(int GroupID)
        {
            bool flag = false;
            try
            {
                flag = GroupHandler.DeleteGroup(GroupID);
            }
            catch (Exception)
            {
                throw;
            }
            return flag;
        }

        public void GetParentGroupList()
        {
            try
            {
                string strJson = JsonConvert.SerializeObject(GroupHandler.GetParentGroupList());
                context.Response.Write(strJson);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public void GetFieldtype(string fieldName)
        {
            try
            {
                string strJsson = string.Empty;
                DataTable dt = GroupHandler.GetFieldType(fieldName);
                if (dt.Rows.Count > 0)
                    strJsson = dt.Rows[0]["DATA_TYPE"].ToString();
                if (fieldName == "DateBirth")
                    strJsson = "datetime";
                context.Response.Write(strJsson);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public void Get_crm_LastResult()
        {
            try
            {
                string strJson = JsonConvert.SerializeObject(GroupHandler.GetResultIDValue());
                context.Response.Write(strJson);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public void GetGroupDataFromQuery(string Type, string Description, string GroupName, string Days, string sortCondition)
        {
            try
            {
                var pageIndex = string.IsNullOrEmpty(context.Request["page"]) ? 1 : int.Parse(context.Request["page"]);
                var pageSize = string.IsNullOrEmpty(context.Request["rows"]) ? 10 : int.Parse(context.Request["rows"]);
                DataSet ds = GroupHandler.GetGroupDataFromQuery(Type, Description, GroupName, Days, pageIndex, pageSize,sortCondition);
                var total = (ds.Tables[0].Rows.Count > 0) ? Convert.ToInt32(ds.Tables[0].Rows[0]["Total"]) : 0;
                string strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                strJson = "{\"total\":\"" + total.ToString() + "\",\"rows\":" + strJson + "}";

                context.Response.Write(strJson);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public void GetTreeGroupList()
        {
            GroupData objParentGroupData;
            List<GroupData> objGroupDataList = null;
            List<GroupData> objParentGroupDataList = null;
            try
            {
                objParentGroupDataList = new List<GroupData>();
                DataTable dt = GroupHandler.GetTreeGroupList();
                foreach (DataRow dr in dt.Rows)
                {
                    if (int.Parse(dr["ParentGroupID"].ToString()) == 0)
                    {
                        objGroupDataList = new List<GroupData>();
                        objParentGroupData = new GroupData();
                        objParentGroupData.id = int.Parse(dr["GroupID"].ToString());
                        objParentGroupData.text = dr["GroupName"].ToString();

                        objGroupDataList = RecursionTreeGroup(objGroupDataList, dt, dr["GroupID"].ToString());
                        objParentGroupData.children = objGroupDataList;
                        objParentGroupDataList.Add(objParentGroupData);
                    }
                }

                string strJson = JsonConvert.SerializeObject(objParentGroupDataList);
                context.Response.Write(strJson);
            }
            catch (Exception)
            {
                throw;
            }
        }

        private List<GroupData> RecursionTreeGroup(List<GroupData> objGroupDataList, DataTable dt, string GroupID)
        {
            GroupData objGroupData;
            List<GroupData> recursiveObjects = new List<GroupData>();

            DataRow[] drParentGroup = dt.Select("ParentGroupID=" + GroupID);
            foreach (DataRow drpg in drParentGroup)
            {
                objGroupData = new GroupData();
                objGroupData.id = int.Parse(drpg["GroupID"].ToString());
                objGroupData.text = drpg["GroupName"].ToString();
                objGroupData.children = RecursionTreeGroup(objGroupDataList, dt, drpg["GroupID"].ToString());
                recursiveObjects.Add(objGroupData);
            }

            return recursiveObjects;
        }

        struct GroupData
        {
            public int id;
            public string text;
            public List<GroupData> children;
        };

        #endregion
    }
}